package juan.happyge.plugin.myi.service.book;

import juan.happyge.plugin.myi.pojo.book.ChapterPojo;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.fontbox.ttf.BufferedRandomAccessFile;

import java.io.*;
import java.nio.charset.Charset;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Stream;

public class BookService {

    private static RandomAccessFile ra = null;
    private static long[] offsetIndex = new long[0];
    private static Integer totalLines = 0;
    private static File file = null;
    private static List<ChapterPojo> bookChapters = new ArrayList<>();

    public static String bookName() {
        return file.getName();
    }

    public static long getBookSize() {
        return file.length();
    }

    public static Integer getTotalLines() {
        return totalLines;
    }

    public static List<ChapterPojo> getBookChapters() {
        return bookChapters;
    }

    /**
     * 加载书籍
     */
    public static void loadBook(String filePath){
        if(StringUtils.isEmpty(filePath)){
            return;
        }
        file = new File(filePath);
        if (!file.exists() || !file.isFile()) {
            return;
        }
        Path path = Paths.get(file.getPath());
        try {
            Stream<String> countStream = Files.lines(path, Charset.forName("utf-8"));
            totalLines = (int) countStream.count();
            offsetIndex = new long[Integer.parseInt(totalLines + "")];
            ra = new BufferedRandomAccessFile(file, "r",8192);
            int i=1;
            while (i < totalLines) {
                String lineContent = ra.readLine();
                if(lineContent == null){
                    return;
                }
                lineContent = new String(lineContent.getBytes("ISO-8859-1"), "utf-8").trim();
                if(analysisChapter(lineContent)){
                    bookChapters.add(new ChapterPojo(bookChapters.size(), lineContent.trim(),  i));
                }
                offsetIndex[i++] = ra.getFilePointer();
            }
        }
        catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 判断章节
     */
    public static Boolean analysisChapter(String lineContent){
        if(lineContent.length() == 0 || lineContent.length() > 30 ){
            return false;
        }
        char[] chars = lineContent.toCharArray();
        if(chars[0] == '第'){
            for (int i = 2; i < chars.length; i++) {
                if(chars[i] == '章' || chars[i] == '节'){
                    return true;
                }
            }
        }
        return false;
    }

    public static String getChapterName(int lineIndex, int pageSize){
        if(CollectionUtils.isEmpty(bookChapters))return null;
        String chapterName = "";
        for (ChapterPojo chapterPojo : bookChapters) {
            if(chapterPojo.getLineIndex() >  lineIndex){
                return chapterName;
            }
            chapterName = chapterPojo.getName();
        }
        return "";
    }

    public static ChapterPojo getChapterInfo(int lineIndex){
        if(CollectionUtils.isEmpty(bookChapters))return null;
        ChapterPojo chapter = null;
        for (ChapterPojo chapterPojo : bookChapters) {
            if(chapterPojo.getLineIndex() >  lineIndex){
                return chapter;
            }
            chapter = chapterPojo;
        }
        return null;
    }

    /**
     * 获取书籍段落，从指定index行开始，获取 line 行数据
     * @param index 指定行
     * @param line  获取行数
     * @return
     */
    public static String getBookParagraph(int index, int line){
        if(ra == null) return null;
        StringBuilder sb = new StringBuilder();
        try {
            ra.seek(offsetIndex[index]);
            if(index + line > totalLines){
                line = totalLines - index;
            }
            for (int i = 0; i < line; i++) {
                String lineContent = new String(ra.readLine().getBytes("ISO-8859-1"), "utf-8");
                sb.append(lineContent + "\r\n");
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return sb.toString();
    }

}
